<template>
<div class="day">
  <div class="select" style="display: inline-flex;">
    <el-form :inline="true" :model="form" class="demo-form-inline" label-position="left">
      <el-form-item label="年月">
        <el-date-picker size="small"
            v-model="form.salaryYearMonth"
            @change="handleCurrentChange(1)"
            type="month"
            placeholder="选择月"
                        :clearable="false">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="员工姓名" :label-width="labelWidth">
      <el-select v-model="form.jobNos" placeholder="请选择员工姓名..." value-key="userId" @change="handleCurrentChange(1)" size="small" :collapse-tags="true" style="width: 20vw;" multiple
                 filterable clearable>
        <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.jobNo" v-for="item in $store.state.userList">
          <span style="float: left">{{ item.userName }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="getDataList">筛选</el-button>
        <el-button size="small" type="primary" @click="exportData">导出</el-button>
        <el-button size="small" type="primary" @click="exportData1">导出全部</el-button>
      </el-form-item>


    </el-form>
  </div>
  <el-table
      :data="tableData"
      stripe
      border
      id="table-detail"
      @selection-change="handleSelectionChange"
      default-expand-all
      :header-cell-style="{'text-align':'center'}"
      :cell-style="{'text-align':'center'}"
      :cell-click="getSelectedData">
    <el-table-column>
      <template slot="header">四川瀚海{{ form.salaryYearMonth|formatDateMonth }}员工每日工资明细表</template>
      <el-table-column label="工资时间" prop="salaryYearMonth" min-width="120">
        <template slot-scope="scope">
          {{ scope.row.salaryYearMonth|formatDateMonth }}
        </template>
      </el-table-column>
      <el-table-column label="工号" prop="jobNo" fixed="left" min-width="100"></el-table-column>
      <el-table-column label="姓名" prop="userName" fixed="left"></el-table-column>
      <el-table-column label="岗位" prop="position" show-overflow-tooltip></el-table-column>
      <el-table-column label="部门" prop="dept" min-width="100" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="薪资属性" prop="salaryAttribute" width="100"></el-table-column>
      <el-table-column label="招聘渠道" prop="recruitmentChannels" width="100"></el-table-column>
      <el-table-column label="招聘渠道" prop="powerType"  width="100"></el-table-column>
      <template v-for="item in monthData">
        <el-table-column :label="item.date+'（'+item.day+'）/'+'元'">
          <el-table-column label="基本工资" :show-overflow-tooltip="true" :prop="'basicWage'+item.dayIndex" width="100">
          </el-table-column>
          <el-table-column label="加班工资" :prop="'overWage'+item.dayIndex" width="100">
          </el-table-column>
          <el-table-column label="当日合计" :prop="'totalWages'+item.dayIndex" width="100">
            <template slot-scope="scope">
              <span @click="getSelectedData(item.year,item.date,scope.row.jobNo)">{{getObjectProperty(scope,item.dayIndex)}}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </template>
    </el-table-column>

  </el-table>
  <div class="block">
    <el-pagination
        hide-on-single-page
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40,total]"
        :page-size=size
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
    </el-pagination>
  </div>

  <el-drawer  :visible="drawer" :before-close="handleClose" size="45%">
    <div slot="title">
      <h3>{{attendanceResult.attendancedate|formatDateBirth}}（星期{{attendanceResult.week}}）出勤信息</h3>
    </div>
    <el-row style="padding: 0 1rem 0 2rem">
      <el-descriptions class="margin-top" title="出勤信息" :column="4" border>
        <template slot="extra">
          <el-button type="primary" size="small">操作</el-button>
        </template>
        <el-descriptions-item label="姓名">
          <span v-text="attendanceResult.fullname"></span>
        </el-descriptions-item>
        <el-descriptions-item label="工号">
          <span v-text="attendanceResult.jobno"></span>
        </el-descriptions-item>
        <el-descriptions-item label="部门">
          <span v-text="attendanceResult.dept"></span>
        </el-descriptions-item>
        <el-descriptions-item label="职位">
          <span v-text="attendanceResult.position"></span>
        </el-descriptions-item>
        <el-descriptions-item label="薪资属性">
          <span v-text="attendanceResult.salarycategory"></span>
        </el-descriptions-item>
        <el-descriptions-item label="招聘渠道">
          <span v-text="attendanceResult.offerchannel"></span>
        </el-descriptions-item>
        <el-descriptions-item label="基本出勤">
          <span v-text="attendanceResult.basicattendance"></span>
        </el-descriptions-item>
        <el-descriptions-item label="基本加班">
          <span v-text="attendanceResult.basicovertime"></span>
        </el-descriptions-item>
        <el-descriptions-item label="连班加班">
          <span v-text="attendanceResult.continuousshifthours"></span>
        </el-descriptions-item>
        <el-descriptions-item label="超时加班">
          <span v-text="attendanceResult.overtime"></span>
        </el-descriptions-item>
        <el-descriptions-item label="总出勤">
          <span v-text="attendanceResult.totalduration"></span>
        </el-descriptions-item>
        <el-descriptions-item label="生产排班">
          <span v-text="attendanceResult.rosteringtype"></span>
        </el-descriptions-item>
        <el-descriptions-item label="薪资排班">
          <span v-text="attendanceResult.salaryrosteringtype"></span>
        </el-descriptions-item>
        <el-descriptions-item label="审批单">
          <span v-text="attendanceResult.tagName"></span>
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <span v-text="attendanceResult.subType"></span>
        </el-descriptions-item>
      </el-descriptions>

    </el-row>

  </el-drawer>
</div>
</template>

<script>
import moment from "moment";

export default {
  name: "PeopleDaySalary",
  data(){
    return{
      monthData:[],
      dingUsersList: [],
      form: {
        salaryYearMonth: moment(moment().subtract(1, "months").startOf('month')).format("YYYY-MM-DD")
      },
      allNum: 0,
      successNum: 0,
      errorNum: 0,
      currentPage: 1,
      total: 0,
      size: 10,
      tableData: [],
      tableData1: [],
      dialogFormVisible: false,
      labelWidth:"75px",
      attendanceResult:{},
      drawer:false
    }
  } ,
  created() {
    this.getUserList()
    this.getDataList()
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.drawer=false
            done();
          })
          .catch(_ => {});
    },
    getObjectProperty(scope,dayIndex) {
      return eval("scope.row.totalWages" +dayIndex);
    },
    handleUserChange() {
      // this.form.userId=
      console.log('Form:', this.form)
      this.getDataList()
    },
    getUserList() {
      axios.get("/ding_users/list").then(res => {
        console.log("用户：", res.data.data)
        this.dingUsersList = res.data.data
      })
    },
    handleClick(tab, event) {
      console.log(tab, event);
      console.log(this.activeName)
      this.getDataList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleEdit(row) {
      console.log(row);
      this.form = row
      this.setDialogVisible(false)
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$tools.showMessageBox("确认删除" + row.paramName + "(" + row.paramValue + ")？", "操作确认", 'warning').then(confirm => {
        axios.delete("/fin_family_allowance/delete/" + row.id).then(res => {
          if (res.data.success) {
            this.$tools.showMessage("参数" + row.paramName + "(" + row.paramValue + ")删除成功！", "success")
            this.getDataList()
          }
        })

      }).catch(cancel => {
        this.$tools.showMessage("操作已取消！", "info")

      })
    },
    getDataList() {
      this.dialogFormVisible = false
      console.log("查询数据：", this.form)
      axios.post("/fin_wages_person_detail_day/list/"+ this.currentPage + "/" + this.size, this.form).then(res => {
            console.log("打卡信息：", res)
            if (res.data.success) {
              this.tableData = res.data.data.records
              this.total = res.data.data.total
              this.pages = res.data.data.pages
              if (this.tableData.length > 0) {
                this.attendanceDate = this.tableData[0].salaryYearMonth
                console.log("ThisAttendanceDate:", this.attendanceDate)
                this.monthData = this.$tools.getMonthData(this.attendanceDate)
              }
            } else {
              this.tableData = []
              this.total = 0
              this.pages = 1

            }
          })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    getDataSummary() {
      switch (this.activeName) {
        case "summary":
          console.log("计算汇总")
          axios.post("/fin_wages_summary/get", this.form).then(res => {
            if (res.data.success) {
              this.getDataList();
            }
          })
          break;
        case "detail":
          console.log("计算详细")
          axios.post("/fin_wages_detail/get", this.form).then(res => {
            if (res.data.success) {
              this.getDataList();
            }
          })
          break;
      }
    },
    exportData() {
      let excelName = '四川瀚海' + moment(this.form.salaryYearMonth).format('YYYY年MM月') + '工资明细表（财务表）.xlsx';
      var xlsxParam = {raw: true};//转换成excel时，使用原始的格式
      // 克隆节点
      let tables = document.getElementById("table-detail").cloneNode(true);
      // 判断是否为固定列，解决（为固定列时，会重复生成表格）
      if (tables.querySelector('.el-table__fixed') !== null) {
        tables.removeChild(tables.querySelector('.el-table__fixed'))
      }
      let table_book = this.$XLSX.utils.table_to_book(tables, xlsxParam);
      var table_write = this.$XLSX.write(table_book, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        this.$FileSaver.saveAs(
            new Blob([table_write], {type: "application/octet-stream"}),
            excelName
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, table_write);
      }
      return table_write;

    },
    exportData1() {
      this.size = this.total
      axios.post("/fin_wages_person_detail_day/list/" + this.currentPage + "/" + this.size, this.form).then(res => {
        console.log("详细：", res)
        if (res.data.success) {
          this.tableData1 = res.data.data.records
          this.total = res.data.data.total
          this.pages = res.data.data.pages
        } else {
          this.tableData1 = []
          this.total = 0
          this.pages = 1
          this.$tools.showMessage(res.data.message, 'error')
        }

      })
      if (this.tableData1.length === this.size) {
        this.exportData()
      }
    },
    getSelectedData(year,date,jobNo){

      let data={
        attendancedate:moment(year+' '+date).format("YYYY-MM-DD"),
        jobno:jobNo
      }
      console.log(data)
      axios.post("/attendance_result_report/getById",data).then(res=>{
        if(res.data.success){
          this.attendanceResult=res.data.data
          this.drawer=true
        }
      })

    }

  },

}
</script>

<style scoped>

</style>
